<template>
  <div class="bg-white p-4 rounded-lg flex flex-col h-full overflow-hidden">
    <!-- 标题栏 -->
    <div class="flex justify-between items-center border-b border-gray-200 pb-4 mb-4">
      <div class="flex items-center space-x-4">
        <h2 class="text-xl font-bold">党员智慧管理驾驶舱</h2>
        <n-space>
          <n-tag type="info">实时洞察发展动态与汇报进度</n-tag>
        </n-space>
      </div>

      <n-space>
        <span class="text-gray-500 text-sm hidden md:inline">最后更新: {{ new Date().toLocaleString() }}</span>
        <n-button @click="refreshData" type="primary">
          <template #icon>
            <RefreshIcon />
          </template>
          刷新数据
        </n-button>
      </n-space>
    </div>

    <!-- 主要内容区域 -->
    <div class="flex-1 min-h-0 overflow-hidden">
      <n-grid :cols="3" :x-gap="24" :y-gap="24" responsive="screen">
        <n-grid-item :span="2">
          <n-card title="积极分子思想汇报详情" :bordered="false" class="h-full">
            <template #header-extra>
              <n-space>
                <n-input v-model:value="searchName" placeholder="按姓名搜索" clearable size="small" />
                <n-select
                  v-model:value="statusFilter"
                  :options="statusOptions"
                  size="small"
                  style="width: 120px"
                />
                <n-button size="small" type="primary">导出数据</n-button>
              </n-space>
            </template>
            
            <n-data-table
              :columns="columns"
              :data="filteredData"
              :pagination="{ pageSize: 8 }"
              :bordered="false"
              :single-line="false"
              flex-height
              style="height: 600px"
            />
          </n-card>
        </n-grid-item>

        <n-grid-item :span="1">
          <n-space vertical :size="24" class="h-full">
            <n-card title="待处理事项" :bordered="false" header-style="color: #d97706;">
              <div class="text-center">
                <div class="text-5xl font-bold text-orange-500 mb-2">{{ delayedCount }}</div>
                <div class="text-gray-500 text-sm mb-4">人思想汇报进度滞后</div>
                <n-button type="warning" @click="handleFilterDelayed" block>
                  一键筛选滞后人员
                </n-button>
              </div>
            </n-card>
            
            <n-card title="党员成分" :bordered="false">
              <div class="chart-container">
                <v-chart :option="pieOptions" autoresize />
              </div>
            </n-card>

            <n-card title="基本数据" :bordered="false">
              <n-grid :cols="2" :x-gap="16" :y-gap="20">
                <n-grid-item>
                  <n-statistic label="党员总数" :value="totalMembers" />
                </n-grid-item>
                <n-grid-item>
                  <n-statistic label="入党积极分子" :value="activists" />
                </n-grid-item>
                <n-grid-item>
                  <n-statistic label="正式党员" :value="activeMembers" />
                </n-grid-item>
                <n-grid-item>
                  <n-statistic label="预备党员" :value="probationaryMembers" />
                </n-grid-item>
              </n-grid>
            </n-card>

          </n-space>
        </n-grid-item>
      </n-grid>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, h } from 'vue';
import { useMessage, NCard, NStatistic, NDataTable, NSpace, NTag, NProgress, NGrid, NGridItem, NPageHeader, NButton, NInput, NSelect } from 'naive-ui';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import VChart from 'vue-echarts';

// ECharts 按需引入
use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
]);

const message = useMessage();

// --- 状态与数据 ---

// 筛选状态
const searchName = ref('');
const statusFilter = ref('all');
const statusOptions = [
  { label: '全部状态', value: 'all' },
  { label: '正常', value: '正常' },
  { label: '延迟', value: '延迟' },
  { label: '严重延迟', value: '严重延迟' },
  { label: '仅看滞后', value: 'delayed' },
];

// 核心统计数据
const totalMembers = ref(0);
const activeMembers = ref(0);
const probationaryMembers = ref(0);
const activists = ref(0);

// 积极分子汇报的原始数据
const activistReportData = ref([]);

// --- 模拟数据 (与原版相同) ---
const mockData = {
  totalMembers: 156,
  activeMembers: 98,
  probationaryMembers: 23,
  activists: 35,
  activistReports: [
     { memberId: "M001", memberName: "张三", studentId: "20210101", studentClass: "软件工程2021-1班", reportCount: 2, requiredCount: 4, lastReportDate: "2024-11-15", status: "正常" }, { memberId: "M002", memberName: "李四", studentId: "20210102", studentClass: "软件工程2021-2班", reportCount: 1, requiredCount: 4, lastReportDate: "2024-10-20", status: "延迟" }, { memberId: "M003", memberName: "王五", studentId: "20210103", studentClass: "计算机科学2021-1班", reportCount: 4, requiredCount: 4, lastReportDate: "2024-12-01", status: "正常" }, { memberId: "M004", memberName: "赵六", studentId: "20210104", studentClass: "数据科学2021-1班", reportCount: 0, requiredCount: 4, lastReportDate: "2024-09-15", status: "严重延迟" }, { memberId: "M005", memberName: "钱七", studentId: "20210105", studentClass: "人工智能2021-1班", reportCount: 3, requiredCount: 4, lastReportDate: "2024-11-28", status: "正常" }, { memberId: "M006", memberName: "孙八", studentId: "20210106", studentClass: "网络工程2021-1班", reportCount: 2, requiredCount: 4, lastReportDate: "2024-11-10", status: "正常" }, { memberId: "M007", memberName: "周九", studentId: "20210107", studentClass: "信息安全2021-1班", reportCount: 0, requiredCount: 4, lastReportDate: "2024-08-30", status: "严重延迟" }, { memberId: "M008", memberName: "吴十", studentId: "20210108", studentClass: "物联网工程2021-1班", reportCount: 1, requiredCount: 4, lastReportDate: "2024-10-05", status: "延迟" }
  ]
};

// --- 计算属性 ---

// 根据筛选条件过滤表格数据
const filteredData = computed(() => {
  return activistReportData.value.filter(item => {
    const nameMatch = item.memberName.includes(searchName.value);
    const statusMatch = statusFilter.value === 'all' || 
                        (statusFilter.value === 'delayed' && (item.status === '延迟' || item.status === '严重延迟')) ||
                        item.status === statusFilter.value;
    return nameMatch && statusMatch;
  });
});

// 滞后人数
const delayedCount = computed(() => {
  return activistReportData.value.filter(item => 
    item.status === '延迟' || item.status === '严重延迟'
  ).length;
});

// 饼图配置
const pieOptions = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} 人 ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: 'center'
  },
  series: [
    {
      name: '党员成分',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '20',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: activeMembers.value, name: '正式党员' },
        { value: probationaryMembers.value, name: '预备党员' }
      ]
    }
  ]
}));


// --- 表格列定义 ---
const columns = [
  { title: '姓名', key: 'memberName', width: 100 },
  { title: '学号', key: 'studentId', width: 120 },
  {
    title: '思想汇报进度',
    key: 'progress',
    render(row) {
      const percentage = (row.reportCount / row.requiredCount * 100);
      let status = 'success';
      if (row.status === '延迟') status = 'warning';
      if (row.status === '严重延迟') status = 'error';
      return h(NProgress, { type: 'line', percentage, status });
    }
  },
  {
    title: '提交数',
    key: 'reportStatus',
    width: 80,
    render: (row) => `${row.reportCount}/${row.requiredCount}`
  },
  { title: '最后提交', key: 'lastReportDate', width: 120 },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render(row) {
      let type = 'success';
      if (row.status === '延迟') type = 'warning';
      if (row.status === '严重延迟') type = 'error';
      return h(NTag, { type, size: 'small' }, { default: () => row.status });
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    render(row) {
      if (row.status !== '正常') {
        return h(NButton, {
          size: 'small',
          type: 'error',
          ghost: true,
          onClick: () => handleRemind(row)
        }, { default: () => '提醒' });
      }
      return null;
    }
  }
];


// --- 方法 ---

// 提醒功能桩
const handleRemind = (row) => {
  message.warning(`已向 ${row.memberName} 发送提醒通知！（模拟）`);
};

// 一键筛选滞后人员
const handleFilterDelayed = () => {
  statusFilter.value = 'delayed';
  searchName.value = ''; // 清空姓名搜索
};

// 数据获取
const fetchMemberStatistics = async () => {
  // 模拟API调用
  setTimeout(() => {
    totalMembers.value = mockData.totalMembers;
    activeMembers.value = mockData.activeMembers;
    probationaryMembers.value = mockData.probationaryMembers;
    activists.value = mockData.activists;
  }, 300);
};

const fetchActivistReports = async () => {
  // 模拟API调用
  setTimeout(() => {
    activistReportData.value = mockData.activistReports;
  }, 500);
};

const refreshData = () => {
  message.loading('正在刷新数据...');
  fetchMemberStatistics();
  fetchActivistReports();
  setTimeout(() => message.success('数据刷新完成！'), 600);
};

// --- 生命周期 ---
onMounted(() => {
  refreshData();
});


// --- 帮助性组件/图标 ---
const RefreshIcon = () => h('svg', { width: '16', height: '16', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: '2', strokeLinecap: 'round', strokeLinejoin: 'round' }, [ h('path', { d: 'M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8' }), h('path', { d: 'M21 3v5h-5' }), h('path', { d: 'M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16' }), h('path', { d: 'M3 21v-5h5' }) ]);
</script>

<style scoped>
.chart-container {
  height: 220px;
  width: 100%;
}

/* 确保页面不会有整体滚动轴 */
</style>